namespace DK.Utils.Schedule;

public class Poller
{
    private readonly Action _loopAction;
    
    private readonly int _loopTime;

    private Task? _runTask;

    private CancellationTokenSource _source = new();

    /// <summary>
    /// 
    /// </summary>
    /// <param name="loopAction"></param>
    /// <param name="loopTime">milliseconds time out</param>
    public Poller(Action loopAction, int loopTime = 1000)
    {
        _loopTime = loopTime;
        _loopAction = loopAction;
    }

    public bool IsCancel => _source.IsCancellationRequested;


    public void Run()
    {
        if (_runTask is { Status: TaskStatus.Running })
        {
            _source.Cancel();
            _runTask.Wait();
        }

        _source = new CancellationTokenSource();
        _runTask = new Task(() =>
        {
            while (!_source.IsCancellationRequested)
            {
                if (_loopAction != null)
                    _loopAction();
                Thread.Sleep(_loopTime);
            }
        });

        _runTask.Start();
    }


    public void Kill()
    {
        _source.Cancel();
        _runTask?.Wait();
    }
}